package com.lpx.demo.demo.util;

import com.lpx.demo.demo.config.listener.SessionListener;
import com.lpx.demo.demo.entity.BaseUserEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

public class SessionUtils {
    /**
     * set注入
     * 获取 httpServletRequest
     */
    private static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        if (ObjectUtils.isEmpty(attributes)) {return null;}
        return attributes.getRequest();
    }
    /**
     * 根据session key 获取value
     * @param key
     * @return
     */
    public static Object getSessionValue(String key){
        HttpServletRequest request = getRequest();
        return request.getSession().getAttribute(key);
    }

    /**
     * 获取 User
     * @return
     */
    public static BaseUserEntity getUser(){
        return  (BaseUserEntity) getSessionValue(Constant.user);

    }
    /**
     *
     * @author
     * @params uid 要强行退出的用户的ID
     * @return
     * @description 通过用户ID来强行把已经在线的用户的登录信息
     */
    @SuppressWarnings("unchecked")
    public static void forceLogoutUser(Long uid) {
        // 删除单一登录中记录的变量
        if (SessionListener.sessionMap.get(uid) != null) {
            HttpSession hs = (HttpSession) SessionListener.sessionMap.get(uid);
            SessionListener.sessionMap.remove(uid);
            Enumeration e = hs.getAttributeNames();
            while (e.hasMoreElements()) {
                String sessionName = (String) e.nextElement();
                // 清空session
                hs.removeAttribute(sessionName);
            }
            // hs.invalidate();
        }
    }
}
